package service

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"post/basic/config"
	"post/handler/model"
	"post/handler/request"
	"post/pkg"
)

func AddPost(c *gin.Context) {
	var form request.AddPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	text := pkg.CheckText(form.Content)
	if text == 2 || text == 3 || text == 4 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "内容审核不合规",
		})
		return
	}
	post := model.Post{
		UserId:    form.UserId,
		Content:   form.Content,
		PostImage: form.PostImage,
		VisRange:  form.VisRange,
	}
	if err := post.AddPost(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "发布帖子失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发布帖子成功",
	})
	return
}
func GetPostList(c *gin.Context) {
	var form request.GetPostList
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	list, err := post.GetPostList(config.DB, form.UserId, form.Page, form.Size)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询公开帖子失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询公开帖子成功",
		"data": gin.H{
			"list": list,
		},
	})
	return
}
func GetMyPost(c *gin.Context) {
	var form request.GetMyPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	list, err := post.GetMyPost(config.DB, form.UserId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询帖子失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询帖子成功",
		"data": gin.H{
			"list": list,
		},
	})
	return
}
func GetPost(c *gin.Context) {
	var form request.GetPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	err := post.GetPost(config.DB, form.PostId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询帖子详情失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询帖子详情成功",
		"data": gin.H{
			"list": post,
		},
	})
	return
}
func DelPost(c *gin.Context) {
	var form request.DelPost
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var post model.Post
	err := post.DelPost(config.DB, form.PostId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "删除帖子失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除帖子成功",
	})
	return
}
